/* 将时间戳格式化为yyyy-MM-dd hh:mm:ss格式，其它格式可自行更改 */
function formatTimeMills(unixtime) {
	// var date = new Date(timeMills);
	// var timeStr = date.getFullYear() + sign;
	// if (date.getMonth() < 9) { // 月份从0开始的
	// 	timeStr += '0';
	// }
	// timeStr += date.getMonth() + 1 + sign;
	// timeStr += date.getDate() < 10 ? ('0' + date.getDate()) : date.getDate();
	// timeStr += ' ';
	// timeStr += date.getHours() < 10 ? ('0' + date.getHours()) : date.getHours();
	// timeStr += ':';
	// timeStr += date.getMinutes() < 10 ? ('0' + date.getMinutes()) : date.getMinutes();
	// timeStr += ':';
	// timeStr += date.getSeconds() < 10 ? ('0' + date.getSeconds()) : date.getSeconds();
	// return timeStr;
	var date = new Date(unixtime);
	var y = date.getFullYear();
	var m = date.getMonth() + 1;
	m = m < 10 ? ('0' + m) : m;
	var d = date.getDate();
	d = d < 10 ? ('0' + d) : d;
	var h = date.getHours();
	h = h < 10 ? ('0' + h) : h;
	var minute = date.getMinutes();
	var second = date.getSeconds();
	minute = minute < 10 ? ('0' + minute) : minute;
	second = second < 10 ? ('0' + second) : second;
	// return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;//年月日时分秒
	return y + '-' + m + '-' + d; //年月日
}

/* 获取今天的零点/最后一刻 */
function getTodayStartOrEnd(sign) {
	let resultTime = '';
	if (sign == 'start') {
		resultTime = new Date(new Date(new Date().toLocaleDateString()).getTime());
	} else if (sign == 'end') {
		resultTime = new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1);
	}
	return formatTimeMills(resultTime, '-');
}


let num = (a) => {
	if (a != null && a.toString() != "") {
		let r = /^-?(0|[1-9]+\d*|[1-9]+\d*\.\d+|0\.\d+)$/;
		if (r.test(a.toString())) {
			return true;
		}
	}
	return false;
}

/* 除法 */
function division(a, b) {
	if (!num(a) || !num(b)) {
		return null;
	}
	let c, d, f, g;
	try {
		c = a.toString().split(".")[1].length;
	} catch (e) {
		c = 0;
	}
	try {
		d = b.toString().split(".")[1].length;
	} catch (e) {
		d = 0;
	}
	f = Number(a.toString().replace(".", ""));
	g = Number(b.toString().replace(".", ""));
	return parseFloat(((f / g) * Math.pow(10, d - c)).toFixed(2))
}

/* 金额格式化 */
function amountFormatting(amount, sign) {
	let changeAmount = 0;
	let resultAmount = 0;
	if (sign == 0) {
		changeAmount = division(amount, 100);
		resultAmount = changeAmount.toFixed(2).replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,');
	} else if (sign == 1) {
		resultAmount = amount.toFixed(0).replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,');
	}
	return resultAmount;
}

export const debounce = (fn, t) => {

	let delay = t || 500;
	let timer;
	return function() {
		let args = arguments;
		if (timer) {
			clearTimeout(timer);
		}
		timer = setTimeout(() => {
			timer = null;

			fn.apply(this, args);
		}, delay)
	}
}

// 将回显的地址码，转为文本供只读组件使用 ,第一个参数为地址码数组，第二,三个参数为省市区的JSON，只有收付通会用到第三个参数
const addressBack = (list, address, addressTow) => {
	if (!list || list.length == 0) return '' // 非空校验

	let addressText = ''

	// 绝大多数清空都没有第二个 地址JSON表
	if (!addressTow) {
		let first = address.find(val => val.value == list[0])
		addressText += first.text + '/'
		let second = first.children.find(val => val.value == list[1])
		addressText += second.text + '/'
		let third = second.children.find(val => val.value == list[2])
		addressText += third.text
	} else {
		// 盛付通 选择 支行所在地址专属 （只能选择到市一级）
		let first = addressTow.find(val => val.value == list[0])
		addressText += first.text + '/'
		let second = first.children.find(val => val.value == list[1])
		addressText += second.text
	}

	return addressText
}

// 将回显的行业mcc码，转为文本供只读组件使用 ,第一个参数为地址码数组，第二参数为行业mcc的JSON, 第三个参数为取值方式，拼接的截取取值，数组的拿最后一个值, 单值等
const mccBack = (mccCode, mccJson, type) => {

	if (!mccCode) return '' // 非空校验
	let mccText = ''

	if (type == 'splicing') {
		let code
		if (mccCode) code = mccCode.split('_')[1]
		for (var i = 0; i < mccJson.length; i++) {
			mccText = mccJson[i].children.find(val => val.value == code)
			if (mccText) break
		}
		mccText = mccText.text
	} else if (type == 'last') {

		for (var i = 0; i < mccJson.length; i++) {
			mccText = mccJson[i].children.find(val => val.value == mccCode)
			if (mccText) break
		}

		mccText = mccText.text
	}

	return mccText
}


function getNowTime() {
	let now = new Date();
	let year = now.getFullYear(); //获取完整的年份(4位,1970-????)
	let month = now.getMonth() + 1; //获取当前月份(0-11,0代表1月)
	let today = now.getDate(); //获取当前日(1-31)
	let hour = now.getHours(); //获取当前小时数(0-23)
	let minute = now.getMinutes(); //获取当前分钟数(0-59)
	let second = now.getSeconds(); //获取当前秒数(0-59)
	let nowTime = ''
	nowTime = year + '-' + fillZero(month) + '-' + fillZero(today) + ' ' + fillZero(hour) + ':' +
		fillZero(minute) + ':' + fillZero(second)
	return nowTime
};

function fillZero(str) {
	var realNum;
	if (str < 10) {
		realNum = '0' + str;
	} else {
		realNum = str;
	}
	return realNum;
}

function compareDate(s1, s2) {
	return new Date(s1.replace(/-/g, '\/')) >= new Date(s2.replace(/-/g, '\/'));
}

// 制作图片
import qrcode from "@/util/qrcode.js";
const drawQRcode = (url) => {
	let params = url; // 二维码参数
	var imgData = qrcode.drawImg(params, {
		typeNumber: 4, // 密度
		errorCorrectLevel: "Q", // 纠错等级
		size: 175, // 白色边框
	});
	return imgData;
}

const drawQRcode1 = (url) => {
	let params = url; // 二维码参数
	// console.log('ssss',url)
	var imgData = qrcode.drawImg(params, {
		typeNumber: 4, // 密度
		errorCorrectLevel: "Q", // 纠错等级
		size: 175, // 白色边框
	});
	return imgData;
}


function checkSfzh(id) {
	// 1 "验证通过!", 0 //校验不通过
	var format = /^(([1][1-5])|([2][1-3])|([3][1-7])|([4][1-6])|([5][0-4])|([6][1-5])|([7][1])|([8][1-2]))\d{4}(([1][9]\d{2})|([2]\d{3}))(([0][1-9])|([1][0-2]))(([0][1-9])|([1-2][0-9])|([3][0-1]))\d{3}[0-9xX]$/;
	//号码规则校验
	if (!format.test(id)) {
		return { 'status': 0, 'msg': '身份证号码不合规' };
	}
	//区位码校验
	//出生年月日校验   前正则限制起始年份为1900;
	var year = id.substr(6, 4), //身份证年
		month = id.substr(10, 2), //身份证月
		date = id.substr(12, 2), //身份证日
		time = Date.parse(month + '-' + date + '-' + year), //身份证日期时间戳date
		now_time = Date.parse(new Date()), //当前时间戳
		dates = (new Date(year, month, 0)).getDate(); //身份证当月天数
	if (time > now_time || date > dates) {
		return { 'status': 0, 'msg': '出生日期不合规' }
	}
	//校验码判断
	var c = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2); //系数
	var b = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'); //校验码对照表
	var id_array = id.split("");
	var sum = 0;
	for (var k = 0; k < 17; k++) {
		sum += parseInt(id_array[k]) * parseInt(c[k]);
	}
	if (id_array[17].toUpperCase() != b[sum % 11].toUpperCase()) {
		return { 'status': 0, 'msg': '身份证校验码不合规' }
	}
	return { 'status': 1, 'msg': '校验通过' }
}

function filterDistance(value) {
	if (!value) return "";
	let val
	if (value && parseFloat(value) > 1000) {
		val = (parseFloat(value) / 1000).toFixed(2) + 'km'
	} else {
		val = parseFloat(value).toFixed(2) + 'm'
	}
	return val;
}
export default {
	formatTimeMills,
	amountFormatting,
	getTodayStartOrEnd,
	addressBack,
	mccBack,
	getNowTime,
	compareDate,
	drawQRcode,
	drawQRcode1,
	division,
	checkSfzh,
	filterDistance,
}